import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:get/get_state_manager/src/simple/get_state.dart';

import '../base/custom_widget.dart';
import '../utils/common.dart';
import '../utils/local_manage.dart';
import '../widget/my_navbar.dart';
import '../widget/primary_btn.dart';
import '../widget/search_text_field.dart';
import 'color_config.dart';
import 'const_config.dart';
import 'http_config.dart';

class ProxyConfigPage extends CustomWidget<ProxyConfigPageController> {

  ProxyConfigPage({Key? key,
    ProxyConfigPageController? controller
  }) : super(
      ProxyConfigPageController(),
      key: key,
      externalController: controller);

  @override
  Widget initView(BuildContext context,
      ProxyConfigPageController controller) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: MyNavBar(
        centerTitle: "设置代理",
        backgroundColor: Colors.white,
      ),
      body: _createBody(controller),
    );
  }

  Widget _createBody(ProxyConfigPageController controller) {

    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          //2.关闭该状态点击确认按钮，将关闭代理，下次进入APP也不会设置代理
          Container(
            padding: EdgeInsets.only(left: 20.w, right: 20.w,top: 20.w),
            child: Text(
              "打开该状态，下次进入APP将自动设置代理为上一次设置的代理",
              style: TextStyle(fontSize: 13.sp, color: ColorConfig.text_gray),
            ),
          ),
          _createSwitch(controller),

          Container(
            height: 1.w,
            color: ColorConfig.bg_color,
          ),
          Container(
            padding: EdgeInsets.only(left: 20.w, right: 20.w,top: 20.w,bottom: 20.w),
            alignment: Alignment.centerLeft,
            child: Text(
              "当前代理为：${controller.getProxyStr()}",
              textAlign: TextAlign.start,
              style: TextStyle(fontSize: 13.sp, color: ColorConfig.text_gray),
            ),
          ),
          Container(
            height: 1.w,
            color: ColorConfig.bg_color,
          ),
          SizedBox(height: 20.w),
          _layoutTextField("请输入ip地址", controller.ipController),
          _layoutTextField("请输入端口号", controller.portController),
          SizedBox(height: 20.w),
          _sureBtn(controller,'代理'),

        ],
      ),
    );
  }

  _createSwitch(ProxyConfigPageController controller) {
    return Container(
      height: 50.w,
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(width: 20.w,),
          Text("开机自动设置代理",
            style: TextStyle(fontSize: 16.sp, color: ColorConfig.FF666666),
          ),

          const Expanded(child: SizedBox()),
          GetBuilder<ProxyConfigPageController>(
              id: controller.idSwitch,
              global: false,
              init: controller,
              builder: (logic) {
            return CupertinoSwitch(
              value: controller.openStaty,
              activeColor: ColorConfig.main,
              onChanged: (value) {
                controller.changeSwitchStaty(value);
              },
            );
          }),
          SizedBox(width: 20.w,),
        ],
      ),
    );
  }

  _layoutTextField(String? hintText,
      MySearchController tfController) {
    return Container(
        margin: EdgeInsets.fromLTRB(12.w, 10.w, 30.w, 0),
        child: Column(
          children: [
            IntrinsicHeight(
              child: SearchTextField(
                controller: tfController,
                textHint: hintText,
              ),
            ),
            Container(
              height: 1.w,
              color: ColorConfig.bg_color,
            ),
          ],
        ));
  }

  _sureBtn(ProxyConfigPageController controller,String? typ) {
    return PrimaryBtn(
      controller: controller.btnController,
      margin: EdgeInsets.fromLTRB(31.w, 5.w, 31.w, 5.w),
      height: 46.w,
      width: double.infinity,
      borderRadius: BorderRadius.circular(5.r),
      background: ColorConfig.main,
      text: "确认",
      textColor: Colors.white,
      textDisabledColor: Colors.white,
      fontSize: 18.sp,
      fontWeight: FontWeight.bold,
      onTap: () async {
        if(typ == '代理'){
          controller.setPort();
        }
      },
    );
  }

}

class ProxyConfigPageController extends GetxController {

  final String idSwitch = "idSwitch";
  final MySearchController ipController =
  MySearchController(showLeftIcon: false, text: "");
  final MySearchController portController =
  MySearchController(showLeftIcon: false, text: "");
  final PrimaryBtnController btnController = PrimaryBtnController();

  final MySearchController normalController =
  MySearchController(showLeftIcon: false, text: "");

  final MySearchController commonController =
  MySearchController(showLeftIcon: false, text: "");

  ProxyConfigPageController();

  bool openStaty = LocalManage.getSp().getBool(ConstConfig.proxyStaty) ?? false;

  setPort() {
    if(openStaty == false){
      HttpConfig.cleanProxy();
      showToast("代理已关闭");
      return;
    }
    if (ipController.getText().isEmpty) {
      showToast("请输入ip地址");
      return;
    }
    if (portController.getText().isEmpty) {
      showToast("请输入端口号");
      return;
    }
    LocalManage.getSp().setString(ConstConfig.proxyIP, ipController.getText());
    LocalManage.getSp().setString(
        ConstConfig.proxyHost, portController.getText());

    if(openStaty == true){
      HttpConfig.setProxy(ipController.getText(), portController.getText());
      showToast("代理设置成功");
    }
  }

  changeSwitchStaty(bool staty){
    openStaty = staty;
    LocalManage.getSp().setBool(ConstConfig.proxyStaty, openStaty);
    update([idSwitch]);
  }

  getProxyStr(){
    String? proxyStr = "--";
    bool localOpenStaty = LocalManage.getSp().getBool(ConstConfig.proxyStaty) ?? false;
    String? ipStr = LocalManage.getSp().getString(ConstConfig.proxyIP);
    String? hostStr = LocalManage.getSp().getString(ConstConfig.proxyHost);
    if(localOpenStaty == true
        && isNotEmptyOrNull(ipStr)
        && isNotEmptyOrNull(hostStr)){
      proxyStr = "$ipStr:$hostStr";
    }
    return proxyStr;
  }

}